const router = require('express').Router();
// var PW = require('png-word');   //生成图片验证码的
// var pw = new PW();
// var R = require('random-word');
// const path = require("path");
var common = require('./common');

// router.get('/', function(req, res){
//   res.session.firstnum = Math.round(Math.random() * 10);
//   res.session.second = Math.round(Math.random() * 10);
//   req.send({
//     status: '0',
//     message: '',
//     data: {
//       firstnum: res.session.firstnum,
//       secondnum: res.session.secondnum
//     }
//   })
// })



// router.get('/vimg', function(req, res){
//   var r = new R("123456");
//   req.session.vimg = r.random(3);
//   pw.createReadStream(req.session.vimg).pipe(res);
//   // pw.createReadStream('1224').pipe(res);
// })

router.post('/', function(req,res){
  let {username, pwd, code} = req.body;
  //console.log(req.body, username, pwd, code);
  common.readFile(common.userFile, function(data){
    users = data;
    if(!users[username]){
      res.send({status:'-1', message: '该用户不存在'});
    } else if(pwd !== users[username].pwd){
      res.send({status: '-1', message: '密码错误'});
    }else if(code !== req.session.vimg){
      res.send({status: '-1', message: '验证码不正确'});
    } else {
      req.session.username = username;
      //console.log('login-session', req.session);
      res.send({status: '0'});
    }
  })
})

//登出
router.post('/logout', function(req,res){
  req.session.username = false;
  res.writeHead(200);
  res.end({status: '0'});
})

module.exports = router;
